package com.lianqi.emcpframework.core.dict.internal;

import com.lianqi.emcpframework.core.dict.ClassDictionary;
import com.lianqi.emcpframework.core.dict.Dictionary;
import com.lianqi.emcpframework.core.dict.DictionaryReposity;
import com.lianqi.emcpframework.core.dict.EnumDict;
import com.lianqi.emcpframework.core.dict.annotation.Dict;
import com.lianqi.emcpframework.core.dict.annotation.Item;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program emcp-framework
 * @ClassName EnumDictionaryReposity
 * @description: 枚举类字典资源管理类
 * @author: sky
 * @create: 2018/11/23 10:26
 */
@Slf4j
public class EnumDictionaryReposity implements DictionaryReposity{

    final static Map<String,Dictionary> parsedDict = new ConcurrentHashMap<>();

    public static void register(Dictionary dictionary){
        if (!parsedDict.containsKey(dictionary.getId())){
            parsedDict.put(dictionary.getId(),dictionary);
        }
    }

    public static <T extends Enum & EnumDict> ClassDictionary parseEnumDict(Class<T> type){
        log.debug("parse enum dict : {}",type);
        Dict annotation = type.getAnnotation(Dict.class);
        EnumClassDictionary dict = new EnumClassDictionary();
        dict.setField("");
        if (annotation != null){
            dict.setId(annotation.id());
            dict.setAlias(annotation.alias());
            dict.setComments(annotation.comments());
            dict.setParserId(annotation.parserId());
            Item[] items = annotation.items();
            List enumDicts = new ArrayList<>();
            if (items != null){

                for (Item item : items){
                    EnumDictionaryItem enumDict = new EnumDictionaryItem();
                    enumDict.setValue(item.value());
                    enumDict.setText(item.text());
                    StringJoiner joiner = new StringJoiner(",");
                    String[] comments = item.comments();
                    for (String s : comments){
                        joiner.add(s);
                    }
                    enumDict.setComments(joiner.toString());
                    enumDicts.add(enumDict);
                }
            }
            dict.setItems(enumDicts);

        }else {
            dict.setId(type.getSimpleName());
            dict.setAlias(type.getName());
            dict.setComments(type.getSimpleName());
        }
        List items = Arrays.asList(type.getEnumConstants());
        if (items != null){
            dict.setItems(items);
        }

        return dict;
    }

    @Override
    public Dictionary findOne(String id) {
        return parsedDict.get(id);
    }

    @Override
    public List<Dictionary> findAll() {
        return new ArrayList<>(parsedDict.values());
    }

    @Override
    public void add(Dictionary define) {
        register(define);
    }
}
